package com.woniuxy.microcouponserver.configure;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;

/**
 * Redis的配置类
 */
@Configuration
public class RedisConfiguration {
    @Resource
    private RedisConnectionFactory factory;
    /**
     * 配置Redis的模板操作类
     * @return
     */
    @Bean
    public RedisTemplate<String,Object> redisTemplate(){
        //由于Redis中存储2进制的数据 ，所以我们可能需要针对k-v进行序列化设置
        RedisTemplate <String,Object> redisTemplate = new RedisTemplate<>();
        //配置获取连接
        redisTemplate.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer valueRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //创建对象的映射
        ObjectMapper mapper = new ObjectMapper();
        //指定需要序列化的域：field getter() 当然也可以控制访问修饰符
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        valueRedisSerializer.setObjectMapper(mapper);
        //针对key的序列化
        StringRedisSerializer keyRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(keyRedisSerializer);
        redisTemplate.setHashKeySerializer(keyRedisSerializer);
        //针对value的序列化

        redisTemplate.setValueSerializer(valueRedisSerializer);
        redisTemplate.setHashValueSerializer(valueRedisSerializer);
        //非Spring注入，将使用下面的方法
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
    /**
     * 针对String类型的对象封装
     * @return
     */
    @Bean
    public ValueOperations<String,Object> valueOperations(){
        return redisTemplate().opsForValue();
    }
    /**
     * 针对List类型的对象封装
     * @return
     */
    @Bean
    public ListOperations<String,Object> listOperations(){
        return redisTemplate().opsForList();
    }
    /**
     * 针对Set类型的对象封装
     * @return
     */
    @Bean
    public SetOperations<String,Object> setOperations(){
        return redisTemplate().opsForSet();
    }
    /**
     * 针对zset类型的对象封装
     * @return
     */
    @Bean
    public ZSetOperations<String,Object> zSetOperations(){
        return redisTemplate().opsForZSet();
    }
    /**
     * 针对Hash类型的对象封装
     * @return
     */
    @Bean
    public HashOperations<String,String,Object> hashOperations(){
        return redisTemplate().opsForHash();
    }
}